#!/bin/bash
############################################################################
# Copyright (C) 2007 Lawrence Livermore National Security, LLC
# Produced at Lawrence Livermore National Laboratory.
# Written by Jim Garlick <garlick@llnl.gov>.
# UCRL-CODE-235119
# 
# This file is part of nfsroot, a network root file system utility.
# 
# nfsroot is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# nfsroot is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with nfsroot; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
############################################################################
#
# rc.nfsroot-bindnfs - nfsroot startup (bindnfs method)
#
# Root is a shared ro nfs file system with configured directories copied into
# /writeable (nfs) and bind mounted back on top if the source directory.
# This is identical to the 'bind' method except writeable is on NFS.
#
export PATH=/bin:/sbin:/usr/bin:/usr/sbin
RAMDIRS="/etc /var"
PREINITPROG=/etc/rc.nfsroot-init
BINDNFS_DIR_MOUNTOPTS="nfsvers=3,rw,nolock"
configfile=/etc/sysconfig/nfsroot
if [ -f $configfile ]; then
    . $configfile
fi
prog=rc.nfsroot-bindnfs

guess_bindnfs_dir () {
   local host
   (while read line; do
      set $line
      if [ "$2" = "/" ] && echo $1|grep -q ":"; then
          echo "$(echo $1|sed 's/:.*//'):/tftpboot/writeable"
          break
      fi
   done) </proc/mounts
}

if touch / 2>/dev/null; then
    echo "${prog}: root file system is read-write" >&2
    return 1 
fi

if [ -z "$BINDNFS_DIR" ]; then
    BINDNFS_DIR=$(guess_bindnfs_dir)
fi
if ! mount -n -o ${BINDNFS_DIR_MOUNTOPTS} ${BINDNFS_DIR} /writeable; then
    echo "${prog}: mount -n -o ${BINDNFS_DIR_MOUNTOPTS} ${BINDNFS_DIR} /writeable failed" >&2
    return 1
fi

umask 022
hostname=`hostname`
if [ -z "$hostname" ]; then
    echo "${prog}: cannot determine hostname" >&2
    umount /writeable
    return 1;
fi
wdir=/writeable/${hostname}


for dir in ${RAMDIRS}; do
    echo "${prog}: copying $dir to writeable NFS"
    mkdir -p ${wdir}${dir}
    if ! rsync -a --delete ${dir}/ ${wdir}${dir} 2>/dev/null; then
        echo "${prog}: copy failed"
        umount /writeable
        return 1
    fi
done
for dir in ${RAMDIRS}; do
    mount -n --bind ${wdir}${dir} ${dir}
done

echo "${prog}: passing control to ${PREINITPROG}" >&2
exec ${PREINITPROG} "$@" </dev/console >/dev/console 2>&1
return 1
